﻿using System.Text.RegularExpressions;

namespace JQuery.WebKit.Common.Utilities
{
    public class Wildcard : Regex
    {
        public Wildcard(string pattern)
            : base(WildcardToRegex(pattern, WildcardPosition.Contains))
        {
        }

        public Wildcard(string pattern, RegexOptions options)
            : base(WildcardToRegex(pattern, WildcardPosition.Contains), options)
        {
        }

        public Wildcard(string pattern, WildcardPosition position)
            : base(WildcardToRegex(pattern, position))
        {
        }

        public Wildcard(string pattern, RegexOptions options, WildcardPosition position)
            : base(WildcardToRegex(pattern, position), options)
        {
        }

        public static string WildcardToRegex(string pattern, WildcardPosition position)
        {
            switch (position)
            {
                case WildcardPosition.StartWith:
                    return "^" + Regex.Escape(pattern).Replace("\\*", ".*").Replace("\\?", ".");
                case WildcardPosition.Contains:
                    return Regex.Escape(pattern).Replace("\\*", ".*").Replace("\\?", ".");
                case WildcardPosition.EndWith:
                    return Regex.Escape(pattern).Replace("\\*", ".*").Replace("\\?", ".") + "$";
                case WildcardPosition.Exact:
                default:
                    return "^" + Regex.Escape(pattern).Replace("\\*", ".*").Replace("\\?", ".") + "$";
            }
            
        }
    }

}
